<script setup lang='ts'>
import { provide, ref, watch } from 'vue';
import { collapseContextKey, CollapseEmits, CollapseProps, type NameType } from './types';

defineOptions({
    name: 'Collapse'
})

const props = defineProps<CollapseProps>()
const emits = defineEmits<CollapseEmits>()

const activeNames = ref<NameType[]>(props.modelValue)
watch(() => props.modelValue, () => {
  activeNames.value = props.modelValue
})
if (props.accordion && activeNames.value.length > 1) {
  console.warn('accordion mode should only have one acitve item')
}

const handleItemClick = (item: NameType) => {
    if (props.accordion) {
        activeNames.value = [ activeNames.value[0] === item ? '' : item ]
    } else {
        const index = activeNames.value.indexOf(item)
        if (index === -1) {
            activeNames.value.push(item)
        } else {
            activeNames.value.splice(index, 1)
        }
    }

    emits('update:modelValue', activeNames.value)
    emits('change', activeNames.value)
}

provide(collapseContextKey, {
  activeNames,
  handleItemClick
})

</script>

<template>
    <div class="vk-collapse">
      <slot/>
    </div>
  </template>

<style lang='scss' scoped>

</style>
